<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Nibbles in PHP GTK</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="GUI, GTK, Nibbles, PHP, Linux, programming">
<meta name="description" content="This part of the PHP GTK tutorial presents Nibbles game clone in PHP GTK.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Nibbles</h1>

<p>
In this part of the PHP GTK programming tutorial, we will create a Nibbles game clone.
</p>

<div class="center">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* top_horizontal */
google_ad_slot = "3327173442";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
<b>Nibbles</b> is an older classic video game. It was first created in late 70s.
Later it was brought to PCs. In this game the player controls a snake.
The objective is to eat as many apples as possible. Each time the snake eats an apple,
its body grows. The snake must avoid the walls and its own body. 
</p>


<h2>Development</h2>

<p>
The size of each of the joints of a snake is 10px. The snake is controlled with 
the cursor keys. Initially, the snake has three joints. The game starts immediately. 
When the game is finished, we display "Game Over" message in the center of the window.
</p>

<p>
The code is split into two files. board.php and nibbles.php. 
</p>

<pre class="code">
&lt;?php

// board.php

define("WIDTH", 300);
define("HEIGHT", 270);
define("DOT_SIZE", 10);
define("ALL_DOTS", WIDTH * HEIGHT / (DOT_SIZE * DOT_SIZE));
define("RAND_POS", 26);
 

class Board extends GtkDrawingArea {

    public function __construct() { 

        parent::__construct(); 

        $this-&gt;modify_bg(Gtk::STATE_NORMAL, new GdkColor(6400, 6400, 6440));
         
        $this-&gt;connect('expose_event', array($this, 'on_expose')); 

        $this-&gt;init_game();

    } 
    
    public function init_game() {

        $this-&gt;x = array_fill(0, ALL_DOTS, 0);
        $this-&gt;y = array_fill(0, ALL_DOTS, 0);

        $this-&gt;left = false;
        $this-&gt;right = true;
        $this-&gt;up = false;
        $this-&gt;down = false;
        $this-&gt;inGame = true;
        $this-&gt;dots = 3;

        for ($i=0; $i&lt;=$this-&gt;dots; $i++) {
            $this-&gt;x[$i] = 50 - $i * 10;
            $this-&gt;y[$i] = 50;
        }
        
        try {
            $this-&gt;dot = CairoImageSurface::createFromPng("dot.png");
            $this-&gt;head = CairoImageSurface::createFromPng("head.png");
            $this-&gt;apple = CairoImageSurface::createFromPng("apple.png");
        } catch( Exception  $e) {
            echo $e-&gt;getMessage();
            echo "cannot load images";
            exit;
        }

        $this-&gt;locate_apple();
        $this-&gt;set_can_focus(true);

        Gtk::timeout_add(100, array($this, 'on_timer'));

     }

    public function on_timer() {

        if ($this-&gt;inGame) {
            $this-&gt;check_apple();
            $this-&gt;check_collision();
            $this-&gt;move();
            $this-&gt;queue_draw();
            return true;
        } else {
            return false;
        }
    }
        

    public function on_expose() {
    
        $cr = $this-&gt;window-&gt;cairo_create();

        if ($this-&gt;inGame) {
            $this-&gt;draw_objects($cr);
        } else {
            $this-&gt;game_over($cr);
        }
    }
    
    public function draw_objects($cr) {
    
        $cr-&gt;SetSourceRgb(0, 0, 0);
        $cr-&gt;paint();

        $cr-&gt;setSourceSurface($this-&gt;apple, 
            $this-&gt;apple_x, $this-&gt;apple_y);
        $cr-&gt;paint();

        for ($z=0; $z&lt;=$this-&gt;dots; $z++) {
            if ($z == 0) {
                $cr-&gt;setSourceSurface($this-&gt;head, 
                    $this-&gt;x[$z], $this-&gt;y[$z]);
                $cr-&gt;paint();
            } else {
                $cr-&gt;setSourceSurface($this-&gt;dot, 
                    $this-&gt;x[$z], $this-&gt;y[$z]);
                $cr-&gt;paint();
            } 
        }
    }

    public function game_over($cr) {

        $c_x = $this-&gt;get_allocation()->width/2;
        $c_y = $this-&gt;get_allocation()->height/2;

        $cr-&gt;SetFontSize(15);
        $cr-&gt;SetSourceRgb(65535, 65535, 65535);

        $te = $cr-&gt;TextExtents("Game Over");
        
        $cr-&gt;MoveTo($c_x - $te['width']/2, $c_y);
        $cr-&gt;ShowText("Game Over");
    }


    public function check_apple() {

        if ($this-&gt;x[0] == $this-&gt;apple_x 
                and $this-&gt;y[0] == $this-&gt;apple_y) {
            $this-&gt;dots = $this-&gt;dots + 1;
            $this-&gt;locate_apple();
        }
    }
    
    public function move() {

        $z = $this-&gt;dots;

        while ($z &gt; 0) {
            $this-&gt;x[$z] = $this-&gt;x[($z - 1)];
            $this-&gt;y[$z] = $this-&gt;y[($z - 1)];
            $z--;
        }

        if ($this-&gt;left) {
            $this-&gt;x[0] -= DOT_SIZE;
        }

        if ($this-&gt;right) {
            $this-&gt;x[0] += DOT_SIZE;
        }

        if ($this-&gt;up) {
            $this-&gt;y[0] -= DOT_SIZE;
        }

        if ($this-&gt;down) {
            $this-&gt;y[0] += DOT_SIZE;
        }
        
     }

    public function check_collision() {

        $z = $this-&gt;dots;
       
        while ($z &gt; 0) {
            if ($z &gt; 4 and $this-&gt;x[0] == $this-&gt;x[$z] 
                       and $this-&gt;y[0] == $this-&gt;y[$z]) {
                $this-&gt;inGame = false;
            }
            $z--;
        }

        if ($this-&gt;y[0] &gt; HEIGHT - DOT_SIZE) {
            $this-&gt;inGame = false;
        }
        
        if ($this-&gt;y[0] &lt; 0) {
            $this-&gt;inGame = false;
        }
        
        if ($this-&gt;x[0] &gt; WIDTH - DOT_SIZE) {
            $this-&gt;inGame = false;
        }
        
        if ($this-&gt;x[0] &lt; 0) {
            $this-&gt;inGame = false;
        }
        
    }

    public function locate_apple() {
    
        $r = rand(0, RAND_POS);
        $this-&gt;apple_x = $r * DOT_SIZE;
        $r = rand(0, RAND_POS);
        $this-&gt;apple_y = $r * DOT_SIZE;
    }

    public function on_key_down($event) {

        $key = $event-&gt;keyval;

        if ($key == Gdk::KEY_Left and !$this-&gt;right) {
            $this-&gt;left = true;
            $this-&gt;up = false;
            $this-&gt;down = false;
        }

        if ($key == Gdk::KEY_Right and !$this-&gt;left) {
            $this-&gt;right = true;
            $this-&gt;up = false;
            $this-&gt;down = false;
        }

        if ($key == Gdk::KEY_Up and !$this-&gt;down) {
            $this-&gt;up = true;
            $this-&gt;right = false;
            $this-&gt;left = false;
        }

        if ($key == Gdk::KEY_Down and !$this-&gt;up) {
            $this-&gt;down = true;
            $this-&gt;right = false;
            $this-&gt;left = false;
        }
    }
}
?&gt;
</pre>

<p>
This is board.php file. 
</p>

<pre class="explanation">
define("WIDTH", 300);
define("HEIGHT", 270);
define("DOT_SIZE", 10);
define("ALL_DOTS", WIDTH * HEIGHT / (DOT_SIZE * DOT_SIZE));
define("RAND_POS", 26);
</pre>

<p>
The WIDTH and HEIGHT constants determine 
the size of the Board. The DOT_SIZE is the size of the apple and the dot
of the snake. The ALL_DOTS constant defines the maximum number of 
possible dots on the Board.
The RAND_POS constant is used to calculate a random position of an apple. 
</p>

<pre class="explanation">
$this-&gt;x = array_fill(0, ALL_DOTS, 0);
$this-&gt;y = array_fill(0, ALL_DOTS, 0);
</pre>

<p>
These two arrays store x, y coordinates of all possible joints of a snake. 
</p>

<p>
The <code>init_game()</code> method initializes variables, loads 
images and starts a timeout function.
</p>

<pre class="explanation">
if ($this-&gt;inGame) {
    $this-&gt;check_apple();
    $this-&gt;check_collision();
    $this-&gt;move();
    $this-&gt;queue_draw();
    return true;
} else {
    return false;
}
</pre>

<p>
Every 140 ms, the <code>on_timer()</code> method is called. If 
we are in the game, we call three methods, that build the logic of the game.
The <code>queue_draw()</code> method forces the widget to be redrawn. This
will reflect the changes of the game on the board. 
Otherwise we return <code>false</code>, which stops the timer event.
</p>


<pre class="explanation">
$cr = $this-&gt;window-&gt;cairo_create();

if ($this-&gt;inGame) {
    $this-&gt;draw_objects($cr);
} else {
    $this-&gt;game_over($cr);
}    
</pre>

<p>
Inside the <code>on_expose()</code> method, we check the <code>$this-&gt;inGame</code>
variable. If it is true, we draw our objects. The apple and the snake joints. 
Otherwise we display "Game over" text.  
</p>

<pre class="explanation">
public function draw_objects($cr) {

    $cr-&gt;SetSourceRgb(0, 0, 0);
    $cr-&gt;paint();

    $cr-&gt;setSourceSurface($this-&gt;apple, 
        $this-&gt;apple_x, $this-&gt;apple_y);
    $cr-&gt;paint();

    for ($z=0; $z&lt;=$this-&gt;dots; $z++) {
        if ($z == 0) {
            $cr-&gt;setSourceSurface($this-&gt;head, 
                $this-&gt;x[$z], $this-&gt;y[$z]);
            $cr-&gt;paint();
        } else {
            $cr-&gt;setSourceSurface($this-&gt;dot, 
                $this-&gt;x[$z], $this-&gt;y[$z]);
            $cr-&gt;paint();
        } 
    }
}
</pre>

<p>
The <code>draw_objects()</code> method draws the apple and the joints of the
snake. The first joint of a snake is its head, which is represented by a red circle. 
</p>


<p>
If the game is over, we call the <code>game_over()</code>
method. This method shows "Game Over" in the center of the window.
</p>

<pre class="explanation">
$c_x = $this-&gt;get_allocation()->width/2;
$c_y = $this-&gt;get_allocation()->height/2;
</pre>

<p>
Here we get the center point of the window. 
</p>

<pre class="explanation">
$cr-&gt;SetFontSize(15);
$cr-&gt;SetSourceRgb(65535, 65535, 65535);
</pre>

<p>
We set the font size and color for the text. The background
is black so the font will be in white color. 
</p>

<pre class="explanation">
$te = $cr-&gt;TextExtents("Game Over");
</pre>

<p>
We get the text extents of the string. This is needed in
order to position the text in the center of the window. 
</p>

<pre class="explanation">
$cr-&gt;MoveTo($c_x - $te['width']/2, $c_y);
$cr-&gt;ShowText("Game Over");
</pre>

<p>
We move to the center and display the text. 
</p>


<pre class="explanation">
public function check_apple() {

    if ($this->x[0] == $this->apple_x 
            and $this->y[0] == $this->apple_y) {
        $this->dots = $this->dots + 1;
        $this->locate_apple();
    }
}
</pre>

<p>
The <code>check_apple()</code> method checks, if the snake has hit
the apple object. If so, we add another snake joint and call the 
<code>locate_apple()</code> method, which randomly places a new apple object. 
</p>

<p>
In the <code>move()</code> method we have the key algorithm of the game. 
To understand it, look at how the snake is moving. You control the head of the snake. 
You can change its direction with the cursor keys. The rest of the joints move
one position up the chain. The second joint moves where the first was, 
the third joint where the second was etc. 
</p>

<pre class="explanation">
while ($z > 0) {
    $this->x[$z] = $this->x[($z - 1)];
    $this->y[$z] = $this->y[($z - 1)];
    $z--;
}
</pre>

<p>
This code moves the joints up the chain. 
</p>

<pre class="explanation">
if ($this-&gt;left) {
    $this-&gt;x[0] -= DOT_SIZE;
}
</pre>

<p>
Move the head to the left.
</p>

<p>
In the <code>check_collision()</code> method, we determine if the snake
has hit itself or one of the walls. 
</p>


<pre class="explanation">
while ($z &gt; 0) {
    if ($z &gt; 4 and $this-&gt;x[0] == $this-&gt;x[$z] 
                and $this-&gt;y[0] == $this-&gt;y[$z]) {
        $this-&gt;inGame = false;
    }
    $z--;
}
</pre>

<p>
Finish the game, if the snake hits one of its joints with the head.
</p>

<pre class="explanation">
if ($this-&gt;y[0] &gt; HEIGHT - DOT_SIZE) {
  $this-&gt;inGame = false;
}
</pre>

<p>
Finish the game, if the snake hits the bottom of the Board. 
</p>

<p>
The <code>locate_apple()</code> method locates an apple randomly 
on the board.
</p>

<pre class="explanation">
$r = rand(0, RAND_POS);
</pre>

<p>
We get a random number from 0 to RAND_POS - 1. 
</p>

<pre class="explanation">
$this-&gt;apple_x = $r * DOT_SIZE;
...
$this-&gt;apple_y = $r * DOT_SIZE;
</pre>

<p>
These lines set the x, y coordinates of the apple
object. 
</p>


<p>
In the <code>on_key_down()</code> method of the Board class, we 
determine the keys that were pressed.
</p>

<pre class="explanation">
if ($key == Gdk::KEY_Left and !$this-&gt;right) {
    $this-&gt;left = true;
    $this-&gt;up = false;
    $this-&gt;down = false;
}
</pre>

<p>
If we hit the left cursor key, we set <code>$this-&gt;left</code> variable to 
true. This variable is used in the <code>move()</code>
method to change coordinates of the snake object. Notice also, that
when the snake is heading to the right, we cannot turn immediately 
to the left. 
</p>

<pre class="code">
&lt;?php
 
/* 
ZetCode PHP GTK tutorial

In this program, we create a Nibbles
game clone. 

author: Jan Bodnar
website: www.zetcode.com
last modified: September 2011
*/

include 'board.php';

class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this-&gt;init_ui();

    } 

    private function init_ui() {

        $this-&gt;set_title('Nibbles');         
        $this-&gt;connect_simple('destroy', array('gtk', 'main_quit')); 

        $this-&gt;board = new Board();
        $this-&gt;board-&gt;connect('key-press-event', array($this, 'on_key_down'));

        $this-&gt;add($this-&gt;board);
      
        $this-&gt;set_default_size(300, 270); 
        $this-&gt;set_position(GTK::WIN_POS_CENTER);
        $this-&gt;show_all();         
    }

    public function on_key_down($sender, $event) {
     
        $key = $event-&gt;keyval;
        $this-&gt;board-&gt;on_key_down($event);
    }
} 
     
new Example(); 
Gtk::main();
 
?&gt;
</pre>

<p>
This is the nibbles.php file. In this file, we set up the Nibbles game. 
</p>

<pre class="explanation">
public function on_key_down($sender, $event) {
  
    $key = $event-&gt;keyval;
    $this-&gt;board-&gt;on_key_down($event);
}
</pre>

<p>
In this class, we catch the key press events. And delegate the processing to the
<code>on_key_down()</code> method of the board class. 
</p>

<img src="/img/gui/phpgtk/nibbles.png" alt="Nibbles">
<div class="figure">Figure: Nibbles</div>


<p>
This was the Nibbles computer game programmed with the GTK library 
and the PHP programming language.
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified September 8, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

